import { Injectable, BadRequestException } from '@nestjs/common';
import { CreateUserDto } from '../user/dto/create-user.dto';
// import { UpdateAuthDto } from './dto/update-auth.dto';
import { User } from '../user/entities/user.entity';
import { Repository, Equal } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcryptjs from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
    private readonly JwtService: JwtService,
  ) {}

  // 注册
  async signup(signupData: CreateUserDto) {
    const findUser = await this.user.findOne({
      where: { username: signupData.username },
    });
    if (findUser && findUser.username === signupData.username)
      return {
        status: -1,
        msg: '用户已存在',
      };
    // 对密码进行加密处理
    signupData.password = bcryptjs.hashSync(signupData.password, 10);
    await this.user.save(signupData);
    return '注册成功';
  }

  // 登录
  async login(loginData: CreateUserDto) {
    const findUser = await this.user.findOne({
      where: { username: loginData.username },
    });
    // 没有找到
    if (!findUser)
      return {
        status: -1,
        msg: '用户不存在',
      };

    // 找到了对比密码
    const compareRes: boolean = bcryptjs.compareSync(
      loginData.password,
      findUser.password,
    );
    // 密码不正确
    if (!compareRes)
      return {
        status: -1,
        msg: '密码不正确',
      };
    const payload = { username: findUser.username };

    return {
      access_token: this.JwtService.sign(payload),
      msg: '登录成功',
    };
  }
}
